import React,{useEffect, useState} from 'react';
import { Button, PageHeader, Modal, Form, Input, message } from 'antd';
import moment from 'moment';
import E from 'wangeditor';
import {ArticleAddApi,ArticleSearchApi,ArticleUpdateApi} from '../request/api'
import {useParams,useNavigate,useLocation} from 'react-router-dom'



let editor = null

export default function Edit() {
  const [content,setContent] = useState('')
  const location = useLocation()
  const [title,setTitle] = useState('')
  const [subTitle,setSubTitle] = useState('')
  const [isModalOpen, setIsModalOpen] = useState(false);
  const navigate = useNavigate()
  const [form] = Form.useForm();
  const params = useParams()

  //111111封装文章请页面跳转
  const dealData = (errCode,msg)=>{
    if(errCode===0){
      // console.log(res);
      message.success(msg)//成功提示
      setIsModalOpen(false);//关闭对话框  
      //成功之后跳回list页面
      setTimeout(() => {
        navigate('/listlist')
      }, 1500);
      
    }else{
      message.error(msg)//失败提示
      setIsModalOpen(false);//关闭对话框
    }
  }

  // console.log(params);

  const showModal = () => {
    setIsModalOpen(true);
  };
  //对话框点击了提交
  const handleOk = () => {
    // setIsModalOpen(false);//关闭对话框
    form
    .validateFields() //validate校验 Fields字段
    .then((values) => {
      // form.resetFields();  //reset重置
      // console.log('Received values of form: ', values);
      let {title,subTitle} = values;

      //地址栏有id代表现在想要更新一篇文章
      if(params.id){
        //更新文章的请求
        ArticleUpdateApi({ 
          title,subTitle,content,id: params.id 
        }).then(res=>{
          // if(res.errCode===0){
          //   // console.log(res);
          //   message.success(res.message)//成功提示
          //   setIsModalOpen(false);//关闭对话框  
          //   //成功之后跳回list页面
          //   setTimeout(() => {
          //     navigate('/listlist')
          //   }, 1500);
            
          // }else{
          //   message.error(res.message)//失败提示
          //   setIsModalOpen(false);//关闭对话框
          // }  
          dealData(res.errCode,res.message)
        })
      }else{
        //拿到表单的值直接做请求,点击提交时请求数据(添加文章)
        ArticleAddApi({ title,subTitle,content }).then(res=>{
          console.log(res);
          // if(res.errCode===0){
          //   // console.log(res);
          //   message.success(res.message)//成功提示
          //   setIsModalOpen(false);//关闭对话框  
          //   //成功之后跳回list页面
          //   setTimeout(() => {
          //     navigate('/listlist')
          //   }, 1500);
            
          // }else{
          //   message.error(res.message)//失败提示
          //   setIsModalOpen(false);//关闭对话框
          // } 
          dealData(res.errCode,res.message)//调用上面封装的函数
        })
      }
      
    })
    //错就错了 直接返回
    .catch(() => {
      return;
    });
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  
  //模拟componentDidMount(挂载完成阶段)
  useEffect(()=>{
    editor = new E("#div1")
    editor.config.onchange = (newHtml) => {
      setContent(newHtml)
    }
    editor.create()

    //根据地址栏id做请求
    if(params.id){
      ArticleSearchApi({id: params.id}).then(res=>{
        if(res.errCode===0){
          let {title,subTitle} = res.data;
          editor.txt.html(res.data.content) // 从新设置编辑器内容
          // console.log(res.data.content);
          setTitle(res.data.title)
          setSubTitle(res.data.subTitle)
        }
      })
    }

    return () =>{
      //组件销毁时销毁编辑器  注：class写法需要在componrntWillUnmount中调用
      editor.destroy()
    }
  },[location.pathname])

  return (
    <div>
      <PageHeader
      ghost={false}
      //文章编辑处的箭头不同路由进入时显示与隐藏
      onBack={params.id ? () => window.history.back() : null}
      title="文章编辑"
      // new Date()获取到当前日期引用moment转换
      subTitle={"当前日期："+moment(new Date()).format("YYYY-MM-DD")}
      extra={<Button key="1" type="primary" onClick={showModal}>提交文章</Button>}
    >
    </PageHeader>
    <div id='div1' style={{padding:'0 20px 20px',background:'#fff'}}></div>
    <Modal zIndex={99999} title="填写文章标题" visible={isModalOpen} onOk={handleOk} onCancel={handleCancel}
     okText="提交" cancelText="取消">
    <Form
      form={form}
      name="basic"
      labelCol={{ span: 3 }}
      wrapperCol={{ span: 21 }}
      autoComplete="off"
      //标题title，和副标题subTitle，默认值
      initialValues={{title: title,subTitle: subTitle}}
    >
      <Form.Item
        label="标题"
        name="title"
        rules={[{ required: true, message: '请填写标题' }]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="副标题"
        name="subTitle"
      >
        <Input />
      </Form.Item>
    </Form>
      </Modal>
    </div>
  )
}
